<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Edit, Plus, Refresh, Search } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import {
  getOwnerController,
  getParkingChargeController,
  getParkingSpaceController,
} from '@/api-client'
import type {
  ParkingChargeQueryRequest,
  ParkingChargeSaveRequest,
  ParkingChargeVO,
} from '@/api-client'

interface ParkingChargeFormModel {
  id?: number
  ownerId?: number
  parkId?: number
  money?: number
  payDate?: string
  endDate?: string
  status?: number
  type?: string
  remarks?: string
}

interface OwnerOption {
  id: number
  name: string
  tel?: string
  houseLabel?: string
}

interface ParkingOption {
  id: number
  numbers: string
  status?: number
}

const chargeApi = getParkingChargeController()
const ownerApi = getOwnerController()
const parkingApi = getParkingSpaceController()

const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref<ParkingChargeVO[]>([])
const total = ref(0)
const selectedRows = ref<ParkingChargeVO[]>([])

const ownerOptions = ref<OwnerOption[]>([])
const ownerLoading = ref(false)
const parkingOptions = ref<ParkingOption[]>([])
const parkingLoading = ref(false)

const pagination = reactive({
  current: 1,
  pageSize: 10,
})

const searchState = reactive({
  payDateRange: [] as string[] | [],
})

const searchForm = reactive<ParkingChargeQueryRequest>({
  current: 1,
  pageSize: 10,
  ownerId: undefined,
  parkNumbers: '',
  status: undefined,
  type: '',
})

const createEmptyForm = (): ParkingChargeFormModel => ({
  id: undefined,
  ownerId: undefined,
  parkId: undefined,
  money: undefined,
  payDate: undefined,
  endDate: undefined,
  status: 0,
  type: '',
  remarks: '',
})

const chargeForm = reactive<ParkingChargeFormModel>(createEmptyForm())
const formRef = ref<FormInstance>()
const dialogVisible = ref(false)
const isEdit = ref(false)

const statusOptions = [
  { label: '未缴', value: 0, type: 'danger' },
  { label: '已缴', value: 1, type: 'success' },
  { label: '部分缴', value: 2, type: 'warning' },
]

const rules = reactive<FormRules<ParkingChargeFormModel>>({
  ownerId: [{ required: true, message: '请选择业主', trigger: 'change' }],
  parkId: [{ required: true, message: '请选择车位', trigger: 'change' }],
  money: [{ required: true, message: '请输入缴费金额', trigger: 'blur' }],
  payDate: [{ required: true, message: '请选择缴费时间', trigger: 'change' }],
})

const formatDate = (value?: string) => {
  if (!value) return '-'
  return dayjs(value).format('YYYY-MM-DD HH:mm')
}

const applySearchRange = () => {
  if (searchState.payDateRange.length === 2) {
    searchForm.payDateFrom = searchState.payDateRange[0]
    searchForm.payDateTo = searchState.payDateRange[1]
  } else {
    searchForm.payDateFrom = undefined
    searchForm.payDateTo = undefined
  }
}

const fetchChargeList = async () => {
  loading.value = true
  applySearchRange()
  try {
    const response = await chargeApi.search3({
      ...searchForm,
      current: pagination.current,
      pageSize: pagination.pageSize,
    })
    if (response.code === 200 && response.data) {
      tableData.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取停车费记录失败')
    }
  } catch (error) {
    console.error('fetchChargeList error:', error)
    ElMessage.error('获取停车费记录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  searchForm.current = 1
  fetchChargeList()
}

const handleReset = () => {
  searchForm.ownerId = undefined
  searchForm.parkNumbers = ''
  searchForm.status = undefined
  searchForm.type = ''
  searchState.payDateRange = []
  handleSearch()
}

const handleSelectionChange = (rows: ParkingChargeVO[]) => {
  selectedRows.value = rows
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  fetchChargeList()
}

const handleCurrentChange = (page: number) => {
  pagination.current = page
  fetchChargeList()
}

const resetForm = () => {
  Object.assign(chargeForm, createEmptyForm())
  formRef.value?.clearValidate()
}

const openDialog = () => {
  dialogVisible.value = true
}

const closeDialog = () => {
  dialogVisible.value = false
  submitLoading.value = false
}

const ownerLabel = (option: OwnerOption) => {
  const parts = [option.name]
  if (option.houseLabel) parts.push(option.houseLabel)
  if (option.tel) parts.push(option.tel)
  return parts.join(' / ')
}

const parkingLabel = (option: ParkingOption) => {
  return `${option.numbers}${option.status === 1 ? '（已占用）' : ''}`
}

const fetchOwnerOptions = async (keyword = '') => {
  ownerLoading.value = true
  try {
    const response = await ownerApi.listOwner({
      current: 1,
      pageSize: 20,
      userName: keyword || undefined,
    })
    if (response.code === 200 && response.data) {
      ownerOptions.value = (response.data.records || []).map<OwnerOption>((item) => ({
        id: item.id!,
        name: item.userName || '未命名业主',
        tel: item.tel || undefined,
        houseLabel: item.houseVO
          ? `${item.houseVO.building?.numbers || ''} ${item.houseVO.numbers || ''}`
          : undefined,
      }))
    }
  } catch (error) {
    console.error('fetchOwnerOptions error:', error)
  } finally {
    ownerLoading.value = false
  }
}

const fetchParkingOptions = async (keyword = '') => {
  parkingLoading.value = true
  try {
    const response = await parkingApi.search2({
      current: 1,
      pageSize: 20,
      numbers: keyword || undefined,
    })
    if (response.code === 200 && response.data) {
      parkingOptions.value = (response.data.records || []).map<ParkingOption>((item) => ({
        id: item.id!,
        numbers: item.numbers || '-',
        status: item.status,
      }))
    }
  } catch (error) {
    console.error('fetchParkingOptions error:', error)
  } finally {
    parkingLoading.value = false
  }
}

const ensureOwnerOption = (owner?: ParkingChargeVO['owner']) => {
  if (!owner?.id) return
  const exists = ownerOptions.value.some((item) => item.id === owner.id)
  if (!exists) {
    ownerOptions.value.push({ id: owner.id, name: owner.name || '未命名业主', tel: owner.tel || undefined })
  }
}

const ensureParkingOption = (space?: ParkingChargeVO) => {
  if (!space?.parkId || !space.parkNumbers) return
  const exists = parkingOptions.value.some((item) => item.id === space.parkId)
  if (!exists) {
    parkingOptions.value.push({ id: space.parkId, numbers: space.parkNumbers, status: space.status })
  }
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  openDialog()
}

const handleEdit = (row: ParkingChargeVO) => {
  isEdit.value = true
  resetForm()
  chargeForm.id = row.id
  chargeForm.ownerId = row.ownerId
  chargeForm.parkId = row.parkId
  chargeForm.money = row.money
  chargeForm.payDate = row.payDate
  chargeForm.endDate = row.endDate
  chargeForm.status = row.status ?? 0
  chargeForm.type = row.type || ''
  chargeForm.remarks = row.remarks || ''
  ensureOwnerOption(row.owner)
  ensureParkingOption({
    parkId: row.parkId,
    parkNumbers: row.parkNumbers,
    status: row.status,
  } as ParkingChargeVO)
  openDialog()
}

const submitForm = async (form: FormInstance | undefined) => {
  if (!form) return
  await form.validate(async (valid) => {
    if (!valid) return
    if (!chargeForm.ownerId || !chargeForm.parkId || chargeForm.money === undefined || !chargeForm.payDate) {
      return
    }

    const payload: ParkingChargeSaveRequest = {
      ownerId: chargeForm.ownerId,
      parkId: chargeForm.parkId,
      money: Number(chargeForm.money),
      payDate: chargeForm.payDate,
      endDate: chargeForm.endDate,
      status: chargeForm.status,
      type: chargeForm.type,
      remarks: chargeForm.remarks,
    }

    submitLoading.value = true
    try {
      if (isEdit.value && chargeForm.id) {
        await chargeApi.update5(chargeForm.id, payload)
        ElMessage.success('更新成功')
      } else {
        await chargeApi.add5(payload)
        ElMessage.success('新增成功')
      }
      closeDialog()
      fetchChargeList()
    } catch (error) {
      console.error('submitForm error:', error)
      ElMessage.error(isEdit.value ? '更新失败，请稍后重试' : '新增失败，请稍后重试')
    } finally {
      submitLoading.value = false
    }
  })
}

const handleDelete = async (row: ParkingChargeVO) => {
  if (!row.id) return
  try {
    await ElMessageBox.confirm('确认删除该停车费记录吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    loading.value = true
    await chargeApi.delete5({ id: row.id })
    ElMessage.success('删除成功')
    fetchChargeList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('handleDelete error:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

const handleBatchDelete = async () => {
  const ids = selectedRows.value
    .map((item) => item.id)
    .filter((id): id is number => id !== undefined)
  if (ids.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }
  try {
    await ElMessageBox.confirm(`确认批量删除选中的 ${ids.length} 条记录吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    loading.value = true
    await chargeApi.deleteBatch3(ids)
    ElMessage.success('批量删除成功')
    fetchChargeList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('handleBatchDelete error:', error)
      ElMessage.error('批量删除失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

const remoteSearchOwner = (keyword: string) => {
  fetchOwnerOptions(keyword)
}

const remoteSearchParking = (keyword: string) => {
  fetchParkingOptions(keyword)
}

onMounted(() => {
  fetchChargeList()
  fetchOwnerOptions()
  fetchParkingOptions()
})
</script>

<template>
  <div class="parking-charge-view">
    <div class="page-header">
      <div>
        <h2>停车费管理</h2>
        <p>登记车位缴费记录，支持按业主、车位及时间筛查。</p>
      </div>
    </div>

    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="业主">
          <el-select
            v-model="searchForm.ownerId"
            placeholder="可选择业主"
            clearable
            filterable
            remote
            :remote-method="remoteSearchOwner"
            :loading="ownerLoading"
            style="width: 220px"
          >
            <el-option
              v-for="item in ownerOptions"
              :key="item.id"
              :label="ownerLabel(item)"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车位编号">
          <el-input
            v-model="searchForm.parkNumbers"
            placeholder="请输入车位编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="缴费状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable style="width: 160px">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="缴费类型">
          <el-input
            v-model="searchForm.type"
            placeholder="例如：月租、临时"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="缴费时间">
          <el-date-picker
            v-model="searchState.payDateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始"
            end-placeholder="结束"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 320px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch"> 搜索 </el-button>
          <el-button :icon="Refresh" @click="handleReset"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="action-section">
      <el-button type="primary" :icon="Plus" @click="handleAdd"> 新增缴费记录 </el-button>
      <el-button
        type="danger"
        :icon="Delete"
        :disabled="selectedRows.length === 0"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
    </div>

    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="业主" min-width="160">
          <template #default="{ row }">
            <div>{{ row.owner?.name || '-' }}</div>
            <div class="cell-sub" v-if="row.owner?.tel">{{ row.owner.tel }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="parkNumbers" label="车位编号" min-width="140" />
        <el-table-column prop="money" label="金额 (元)" width="120">
          <template #default="{ row }">￥{{ row.money?.toFixed(2) ?? '0.00' }}</template>
        </el-table-column>
        <el-table-column prop="payDate" label="缴费时间" min-width="180">
          <template #default="{ row }">{{ formatDate(row.payDate) }}</template>
        </el-table-column>
        <el-table-column prop="endDate" label="到期日期" min-width="160">
          <template #default="{ row }">{{ row.endDate || '-' }}</template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : row.status === 2 ? 'warning' : 'danger'">
              {{ row.status === 1 ? '已缴' : row.status === 2 ? '部分缴' : '未缴' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="缴费类型" min-width="120" />
        <el-table-column prop="remarks" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="{ row }">
            <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑缴费记录' : '新增缴费记录'"
      width="560px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="chargeForm" :rules="rules" label-width="100px">
        <el-form-item label="关联业主" prop="ownerId">
          <el-select
            v-model="chargeForm.ownerId"
            placeholder="请选择业主"
            clearable
            filterable
            remote
            :remote-method="remoteSearchOwner"
            :loading="ownerLoading"
            style="width: 100%"
          >
            <el-option
              v-for="item in ownerOptions"
              :key="item.id"
              :label="ownerLabel(item)"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车位" prop="parkId">
          <el-select
            v-model="chargeForm.parkId"
            placeholder="请选择车位"
            clearable
            filterable
            remote
            :remote-method="remoteSearchParking"
            :loading="parkingLoading"
            style="width: 100%"
          >
            <el-option
              v-for="item in parkingOptions"
              :key="item.id"
              :label="parkingLabel(item)"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="缴费金额" prop="money">
          <el-input v-model.number="chargeForm.money" type="number" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="缴费时间" prop="payDate">
          <el-date-picker
            v-model="chargeForm.payDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择缴费时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="chargeForm.endDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="缴费状态">
          <el-radio-group v-model="chargeForm.status">
            <el-radio :label="item.value" v-for="item in statusOptions" :key="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="缴费类型">
          <el-input v-model="chargeForm.type" placeholder="例如：月租、临时" maxlength="20" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="chargeForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm(formRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="css" scoped>
.parking-charge-view {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.page-header h2 {
  margin: 0 0 6px;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 13px;
}

.search-section,
.action-section,
.table-section,
.pagination-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
}

.search-section {
  margin-bottom: 16px;
}

.action-section {
  display: flex;
  gap: 12px;
  align-items: center;
  margin: 16px 0;
}

.table-section {
  margin-bottom: 16px;
}

.pagination-section {
  text-align: right;
}

.cell-sub {
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  text-align: right;
}
</style>
